package org.spdata.tsdb.coder;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import org.spdata.utils.ByteUtils;

/**
 * 重复整数片段编码器
 */
public class RepeatIntCoder {
	/**
	 * 整数序列中重复的值
	 */
	Integer value = null;

	/**
	 * 当前重复片段在原始序列中的起始位置和结束位置
	 */
	int from = 0,end = 0;
	
	
	
	public int getFrom() {
		return from;
	}

	public void setFrom(int from) {
		this.from = from;
	}

	public int getEnd() {
		return end;
	}

	public void setValue(Integer value) {
		this.value = value;
	}

	public RepeatIntCoder(int value,int from) {
		this.value = value;
		this.from = from;
		this.end = from;
	}
	
	public Integer getValue() {
		return this.value;
	}
	
	public void setEnd(int end) {
		this.end = end;
	}

	//去重编码：[2个byte 值大小，2byte起始位置,2byte 重复次数]
	public byte[] encode(){
		ByteArrayOutputStream out = new ByteArrayOutputStream();			
		if(Math.abs(value)<=0x7FFF) {
			//重复值大小
			out.write(ByteUtils.changeIntTo2Bytes(value),0,2);
			//在原序列中的起始位置
			out.write(ByteUtils.changeIntTo2Bytes(from),0,2);
			//重复多少次
			out.write(ByteUtils.changeIntTo2Bytes(end-from+1),0,2);
		}else {
			throw new RuntimeException("不支持对>0x7FFF 的整数进行压缩编码");
		}
		return out.toByteArray();
	}
	
	public static Map<String,Integer> decode(byte[] bytes) {
		int v = ByteUtils.changeBytesToInt(bytes[0],bytes[1]);
		int from = ByteUtils.changeBytesToInt(bytes[2],bytes[3]);
		int count = ByteUtils.changeBytesToInt(bytes[4],bytes[5]);
		Map<String,Integer> r = new HashMap<String,Integer>();
		r.put("value", v);
		r.put("from", from);
		r.put("count", count);
		return r;
	}
	
	public static Map<String,Integer> decode(byte[] bytes,int from ,int len){
		byte[] section = new byte[len];
		System.arraycopy(bytes, from, section, 0, len);
		return decode(section);
	}
}
